package mr.ali.videoapp.portal.service.impl;

import lombok.extern.slf4j.Slf4j;
import org.json.JSONObject;
import org.springframework.stereotype.Service;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.HttpURLConnection;
import java.net.URL;
import java.net.URLEncoder;

@Service
@Slf4j
public class WechatPhoneService {

    private static final String APP_ID = "wx6c0d4bf9d99cc8b3";
    private static final String APP_SECRET = "505f947335f37da0c1bfe9181a2edb6f";
    private static final String GET_VERIFY_INFO_URL = "https://api.weixin.qq.com/donut/code2verifyinfo";

    public JSONObject getVerifyInfo(String code) throws Exception {
        log.info("前端获取的 code: {}", code);
        if (code == null || code.isEmpty()) {
            throw new IllegalArgumentException("Invalid code");
        }

        // 构建请求 URL
        String requestUrl = buildRequestUrl(code);
        log.info("请求微信服务器获取用户信息的 URL: {}", requestUrl);

        // 发送 HTTP 请求
        return sendHttpRequest(requestUrl);
    }

    private String buildRequestUrl(String code) throws Exception {
        return GET_VERIFY_INFO_URL + "?appid=" + URLEncoder.encode(APP_ID, "UTF-8") +
                "&appsecret=" + URLEncoder.encode(APP_SECRET, "UTF-8") +
                "&code=" + URLEncoder.encode(code, "UTF-8") +
                "&grant_type=authorization_code";
    }

    private JSONObject sendHttpRequest(String requestUrl) throws Exception {
        URL url = new URL(requestUrl);
        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
        conn.setRequestMethod("GET");

        try {
            // 检查 HTTP 响应码
            int responseCode = conn.getResponseCode();
            log.info("微信服务器响应码: {}", responseCode);
            if (responseCode != 200) {
                throw new RuntimeException("Failed : HTTP error code : " + responseCode);
            }

            // 读取响应内容
            BufferedReader in = new BufferedReader(new InputStreamReader(conn.getInputStream()));
            String inputLine;
            StringBuilder response = new StringBuilder();
            while ((inputLine = in.readLine()) != null) {
                response.append(inputLine);
            }
            in.close();

            // 解析 JSON 响应
            JSONObject jsonResponse = new JSONObject(response.toString());
            log.info("微信服务器响应内容: {}", jsonResponse);
            // 解析 JSON 字符串为 JSONObject

            // 提取 errcode
            int errcode = jsonResponse.getInt("errcode");
            System.out.println("errcode: " + errcode);

            // 提取 login_info 相关信息
            JSONObject loginInfo = jsonResponse.getJSONObject("login_info");
            if (loginInfo != null) {
                long loginTime = loginInfo.getLong("login_time");
                String type = loginInfo.getString("type");
                System.out.println("login_time: " + loginTime);
                System.out.println("type: " + type);
            }

            // 提取 user_info 相关信息
            JSONObject userInfo = jsonResponse.getJSONObject("user_info");
            if (userInfo != null) {
                String userId = userInfo.getString("user_id");
                System.out.println("user_id: " + userId);

                // 提取 phone_info 相关信息
                JSONObject phoneInfo = userInfo.getJSONObject("phone_info");
                if (phoneInfo != null) {
                    String phone = phoneInfo.getString("phone");
                    System.out.println("phone: " + phone);
                }
            }

            // 提取 errmsg
            String errmsg = jsonResponse.getString("errmsg");
            System.out.println("errmsg: " + errmsg);
            return jsonResponse;
        } finally {
            conn.disconnect();
        }
    }
}